package com.atgulimall.com.cart.web;

import com.atgulimall.com.cart.service.CartService;
import com.atgulimall.com.cart.vo.Cart;
import com.atgulimall.com.cart.vo.CartItem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.List;
import java.util.concurrent.ExecutionException;

/**
 * @author 满超
 * @date 2020/06/20
 **/
@Controller
public class IndexCartController {

    @Autowired
    CartService cartService;

    @ResponseBody
    @GetMapping("/getCartItems")
    public List<CartItem> getItem(){
        return cartService.getItem();
    }

    //购物车主页
    @GetMapping("/cart.html")
    public String list(Model model) throws ExecutionException, InterruptedException {
        //通过拦截器快速得到用户信息，id，user-key
        Cart cart = cartService.getCart();
        model.addAttribute("cart",cart);
        return "cart";
    }

    //添加商品到购物车
    @GetMapping("/addToCart")
    public String addToCart(@RequestParam("skuId") Long skuId, @RequestParam("num") Integer num, RedirectAttributes attributes) throws ExecutionException, InterruptedException {

        //只添加一次就重定向走了，避免在听一个页面刷新导致不停增加数量
        cartService.addToCart(skuId, num);

        attributes.addAttribute("skuId", skuId);

        return "redirect:http://cart.gulimall.com/addCartSuccess.html";
    }

    @GetMapping("/addCartSuccess.html")
    public String addCartSuccess(@RequestParam("skuId") Long skuId, Model model){

        CartItem cartItem = cartService.getCartItem(skuId);
        model.addAttribute("item", cartItem);
        return "success";
    }

    //勾选购物项
    @GetMapping("/checkItem")
    public String checkItem(@RequestParam("skuId") Long skuId,@RequestParam("check") Integer check){
        cartService.checkItem(skuId, check);
        return "redirect:http://cart.gulimall.com/cart.html";
    }

    @GetMapping("/number")
    public String num(@RequestParam("skuId") Long skuId,@RequestParam("num") Integer num){
        cartService.num(skuId,num);
        return "redirect:http://cart.gulimall.com/cart.html";
    }

    //删除
    @GetMapping("/del")
    public String clearCart(@RequestParam("skuId") Long skuId){
        cartService.del(skuId);
        return "redirect:http://cart.gulimall.com/cart.html";
    }
}
